package com.sgb.kjwl.viewmodel.transport;

import android.app.Application;
import android.content.Context;
import android.graphics.Color;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.lifecycle.AndroidViewModel;
import androidx.lifecycle.MutableLiveData;

import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.model.BitmapDescriptor;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.LatLngBounds;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.maps.model.PolylineOptions;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.route.BusRouteResult;
import com.amap.api.services.route.DrivePath;
import com.amap.api.services.route.DriveRouteResult;
import com.amap.api.services.route.DriveStep;
import com.amap.api.services.route.RideRouteResult;
import com.amap.api.services.route.RouteSearch;
import com.amap.api.services.route.WalkRouteResult;
import com.sgb.kjwl.R;
import com.sgb.kjwl.api.APIManager;
import com.sgb.kjwl.api.NewAPIManager;
import com.sgb.kjwl.model.entity.transport.DriverLocationVo;
import com.sgb.kjwl.model.entity.transport.OperateGoodsSourcePlaceVO;
import com.sgb.kjwl.model.entity.transport.PayInfoEntity;
import com.sgb.kjwl.model.entity.transport.TransportOrderEntity;
import com.sgb.kjwl.view.widget.transport.RealRouteOverlay;
import com.swgk.core.base.model.entity.BaseEntity;
import com.swgk.core.dialog.DialogHelper;
import com.swgk.core.util.MLog;
import com.swgk.core.util.MToast;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Time:2021/3/9
 * Author:黄淋
 * Description:运输订单详情
 */
public class TransportOrderDetailModel extends AndroidViewModel {

    public MutableLiveData<TransportOrderEntity> ldDetails = new MutableLiveData<>();
    public MutableLiveData<PayInfoEntity> ldTradeNo = new MutableLiveData<>();
    public MutableLiveData<PayInfoEntity> ldTradeNoFreight = new MutableLiveData<>();
    public MutableLiveData<String> ldSureOrder = new MutableLiveData<>();
    public MutableLiveData<Boolean> ldMapLoadFinish = new MutableLiveData<>();
    //装卸点经纬度信息
    private List<LatLonPoint> sourcePoints = new ArrayList<>();
    //司机实时轨迹点信息
    private List<LatLonPoint> realPoints = new ArrayList<>();
    private List<LatLng> realLatLngs = new ArrayList<>();
    //货源信息标记集合
    private List<MarkerOptions> markerOptions = new ArrayList<>();
    private String handleTypeNo;

    private List<DriverLocationVo> locationList = new ArrayList<>();
    private RouteSearch planRouteSearch;
    private RouteSearch realRouteSearch;
    private AMap aMap;
    private List<LatLng> latLngs = new ArrayList<>();
    //支付信息费超时提示
    public MutableLiveData<Boolean> ldTimeout = new MutableLiveData<>();

    private Context context;

    public TransportOrderDetailModel(@NonNull Application application) {
        super(application);
        this.context = application;
    }

    public void getDetailData(Context context, Map map) {
        DialogHelper.showProgressDialog(context, null, "请求中...", 0, false, null).setCanceledOnTouchOutside(false);
        NewAPIManager.getInstance().getLogisticsAPI().getShippingOrderDetail(map).enqueue(new Callback<BaseEntity<TransportOrderEntity>>() {
            @Override
            public void onResponse(Call<BaseEntity<TransportOrderEntity>> call, Response<BaseEntity<TransportOrderEntity>> response) {
                DialogHelper.dismissProgressDialog();
                if (response.body() == null || response.body().getState() == null || response.body().getData() == null)
                    return;

                if (response.body().getState().equals("ok")) {
                    ldDetails.postValue(response.body().getData());
                } else {
                    MToast.showToast(context, response.body().getMsg());
                }
            }

            @Override
            public void onFailure(Call<BaseEntity<TransportOrderEntity>> call, Throwable t) {
                DialogHelper.dismissProgressDialog();
            }
        });
    }

    /**
     * 确认订单
     *
     * @param orderNo
     */
    public void getSureOrder(Context context, String orderNo) {
        Map map = new HashMap();
        map.put("orderNo", orderNo);
        DialogHelper.showProgressDialog(context, null, "请求中...", 0, false, null).setCanceledOnTouchOutside(false);
        APIManager.getInstance().getDriverAPI().sureOrder(map).enqueue(new Callback<BaseEntity<TransportOrderEntity>>() {
            @Override
            public void onResponse(Call<BaseEntity<TransportOrderEntity>> call, Response<BaseEntity<TransportOrderEntity>> response) {
                DialogHelper.dismissProgressDialog();
                if (response.body() == null || response.body().getState() == null || response.body().getData() == null)
                    return;

                if (response.body().getState().equals("ok")) {
                    ldSureOrder.postValue("");
                } else {
                    MToast.showToast(context, response.body().getMsg());
                }
            }

            @Override
            public void onFailure(Call<BaseEntity<TransportOrderEntity>> call, Throwable t) {
                DialogHelper.dismissProgressDialog();
            }
        });
    }


    /**
     * 支付运费
     *
     * @param orderNo
     */
    public void getPayFreight(Context context, String orderNo) {
        Map map = new HashMap();
        map.put("orderNo", orderNo);
        DialogHelper.showProgressDialog(context, null, "请求中...", 0, false, null).setCanceledOnTouchOutside(false);
        APIManager.getInstance().getDriverAPI().payFreight(map).enqueue(new Callback<BaseEntity<PayInfoEntity>>() {
            @Override
            public void onResponse(Call<BaseEntity<PayInfoEntity>> call, Response<BaseEntity<PayInfoEntity>> response) {
                DialogHelper.dismissProgressDialog();
                if (response.body() == null || response.body().getState() == null || response.body().getData() == null)
                    return;

                if (response.body().getState().equals("ok") && response.body().getData().getResult().equals("200")) {
                    ldTradeNo.postValue(response.body().getData());
                } else {
                    MToast.showToast(context, response.body().getData().getMessage());
                }
            }

            @Override
            public void onFailure(Call<BaseEntity<PayInfoEntity>> call, Throwable t) {
                DialogHelper.dismissProgressDialog();
            }
        });
    }

    /**
     * 支付运费(无信息费)
     *
     * @param orderNo
     */
    public void getPayFreightInfo(Context context, String orderNo) {
        Map map = new HashMap();
        map.put("orderNo", orderNo);
        DialogHelper.showProgressDialog(context, null, "请求中...", 0, false, null).setCanceledOnTouchOutside(false);
        APIManager.getInstance().getDriverAPI().payFreight(map).enqueue(new Callback<BaseEntity<PayInfoEntity>>() {
            @Override
            public void onResponse(Call<BaseEntity<PayInfoEntity>> call, Response<BaseEntity<PayInfoEntity>> response) {
                DialogHelper.dismissProgressDialog();
                if (response.body() == null || response.body().getState() == null || response.body().getData() == null)
                    return;

                if (response.body().getState().equals("ok") && response.body().getData().getResult().equals("200")) {
                    ldTradeNoFreight.postValue(response.body().getData());
                } else {
                    MToast.showToast(context, response.body().getData().getMessage());
                }
            }

            @Override
            public void onFailure(Call<BaseEntity<PayInfoEntity>> call, Throwable t) {
                DialogHelper.dismissProgressDialog();
            }
        });
    }

    private TransportOrderEntity orderEntity;

    /**
     * 加载地图信息
     *
     * @param orderEntity
     * @param aMap
     */
    public void loadMapInfo(TransportOrderEntity orderEntity, AMap aMap) {
        this.orderEntity = orderEntity;
        this.aMap = aMap;
        aMap.clear();
        markerOptions.clear();
        latLngs.clear();
        //显示司机的当前位置
        if (orderEntity.getStatus() != null)
            switch (orderEntity.getStatus()) {
                case 1://待确认
                case 2://待发车
                case 3://运输中
                    if (orderEntity.getLongitude() > 0 && orderEntity.getLatitude() > 0) {
                        String address = orderEntity.getProvinceName() + orderEntity.getCityName() + orderEntity.getDistrictName();
                        if (TextUtils.isEmpty(address)) {
                            address = "定位中...";
                        }
                        LatLng driverPosition = new LatLng(orderEntity.getLatitude(), orderEntity.getLongitude());
                        markerOptions.add(createMarker(driverPosition, address, 3));
                        latLngs.add(driverPosition);
                    }
                    break;

                default:
                    break;
            }
        setPlanRouteInfo();
    }

    /**
     * 预置路径信息
     */
    private void setPlanRouteInfo() {
        if (orderEntity == null)
            return;
        handleTypeNo = orderEntity.getHandleTypeNo();
        //装载 装卸地经纬度
        if (orderEntity.getPlace() != null) {
            OperateGoodsSourcePlaceVO place = orderEntity.getPlace();
            LatLonPoint sendPoint = null;
            LatLng sendLL = null;
            if (place.getLatitude() > 0 && place.getLongitude() > 0) {
                sendPoint = new LatLonPoint(place.getLatitude(), place.getLongitude());
                sendLL = new LatLng(place.getLatitude(), place.getLongitude());
            }

            LatLonPoint viaSendPoint = null;
            if (place.getViaSendLatitude() > 0 && place.getViaSendLongitude() > 0) {
                viaSendPoint = new LatLonPoint(place.getViaSendLatitude(), place.getViaSendLongitude());
            }
            LatLonPoint viaDestPoint = null;
            if (place.getViaDestLatitude() > 0 && place.getViaDestLongitude() > 0) {
                viaDestPoint = new LatLonPoint(place.getViaDestLatitude(), place.getViaDestLongitude());
            }

            LatLonPoint destPoint = null;
            LatLng destLL = null;
            if (place.getDestLatitude() > 0 && place.getDestLongitude() > 0) {
                destPoint = new LatLonPoint(place.getDestLatitude(), place.getDestLongitude());
                destLL = new LatLng(place.getDestLatitude(), place.getDestLongitude());
            }

            sourcePoints.clear();
            switch (handleTypeNo) {
                case "11":
                    sourcePoints.add(sendPoint);
                    sourcePoints.add(destPoint);
                    break;
                case "21":
                    sourcePoints.add(sendPoint);
                    sourcePoints.add(viaSendPoint);
                    sourcePoints.add(destPoint);
                    break;
                case "12":
                    sourcePoints.add(sendPoint);
                    sourcePoints.add(viaDestPoint);
                    sourcePoints.add(destPoint);
                    break;
                case "22":
                    sourcePoints.add(sendPoint);
                    sourcePoints.add(viaSendPoint);
                    sourcePoints.add(viaDestPoint);
                    sourcePoints.add(destPoint);
                    break;
            }

            //起点
            markerOptions.add(createMarker(sendLL, place.getCityName(), 1));
            //终点
            markerOptions.add(createMarker(destLL, place.getDestCityName(), 2));
            planningLoadingRoute(sourcePoints, 1);
        }
    }

    /**
     * 设置实际路线信息
     */
    private void setRealityRouteInfo(TransportOrderEntity orderEntity) {
        if (orderEntity != null && orderEntity.getLocationList() != null && orderEntity.getLocationList().size() >= 2) {
            locationList.clear();
            locationList.addAll(orderEntity.getLocationList());
            realPoints.clear();
            realLatLngs.clear();
            for (DriverLocationVo locationVo : locationList) {
                if (locationVo.getLatitude() > 0 && locationVo.getLongitude() > 0) {
                    realPoints.add(new LatLonPoint(locationVo.getLatitude(), locationVo.getLongitude()));
                    LatLng latLng = new LatLng(locationVo.getLatitude(), locationVo.getLongitude());
                    realLatLngs.add(latLng);
                    latLngs.add(latLng);
                }
            }

            aMap.addPolyline(new PolylineOptions()
                            .addAll(realLatLngs).width(20)
                            .setCustomTexture(BitmapDescriptorFactory.fromResource(R.drawable.icon_path_green))//纹理
//                    .color(Color.argb(255, 6, 199, 100))//纯色
            );

//            planningLoadingRoute(realPoints, 2);
        }

        //添加所有marker
        for (MarkerOptions sourceMarker : markerOptions) {
            aMap.addMarker(sourceMarker);
        }

        //显示完整地图路线
        LatLngBounds.Builder builder = new LatLngBounds.Builder();
        for (int i = 0; i < latLngs.size(); i++) {
            builder.include(latLngs.get(i));
        }
        //显示全部路径点,第二个参数是四周留空宽度
        aMap.moveCamera(CameraUpdateFactory.newLatLngBounds(builder.build(), 100));
        ldMapLoadFinish.postValue(true);

    }

    /**
     * 添加需要规划的路线数据，并开启异步查询
     *
     * @param points 路线连接点
     * @param type   规划路线的类型：1——计划，2——实际
     */
    public void planningLoadingRoute(List<LatLonPoint> points, int type) {
        //路线点不能少于两个
        if (points == null || points.size() < 2) {
            return;
        }
        List<LatLonPoint> passedByPoints = null;
        //设置开始位置坐标点(注意经纬度不能写反,会报错1800(只能规划到中国区域里的地图路线))
        LatLonPoint startPoint = points.get(0);
        //设置目的地坐标点
        LatLonPoint endPoint = points.get(points.size() - 1);
        //查询信息对象
        RouteSearch.FromAndTo fromAndTo = new RouteSearch.FromAndTo(startPoint, endPoint);

        if (points.size() > 2) {
            passedByPoints = new ArrayList<>();
            for (int i = 1; i < points.size() - 1; i++) {
                passedByPoints.add(points.get(i));
            }
        }
        //设置搜索参数 1.fromAndTo 路径的起点终点  2.路径规划的策略（可选），默认为“躲避拥堵” 3.途经点，可选 4.避让区域，可选， 5.货车大小 ,默认轻型车
        RouteSearch.DriveRouteQuery query = new RouteSearch.DriveRouteQuery(
                fromAndTo,
                RouteSearch.DRIVING_SINGLE_SHORTEST,
                passedByPoints,
                null,
                "");

        if (type == 1) {
            if (planRouteSearch == null)
                planRouteSearch = new RouteSearch(context);
            // 搜索监听
            planRouteSearch.setRouteSearchListener(new OnPlanListener());
            //开始异步查询
            planRouteSearch.calculateDriveRouteAsyn(query);
        } else if (type == 2) {
            if (realRouteSearch == null)
                realRouteSearch = new RouteSearch(context);
            // 搜索监听
            realRouteSearch.setRouteSearchListener(new OnRealListener());
            //开始异步查询
            realRouteSearch.calculateDriveRouteAsyn(query);
        }
    }


    /**
     * 路线规划回调类
     */
    private class OnPlanListener implements RouteSearch.OnRouteSearchListener {

        @Override
        public void onBusRouteSearched(BusRouteResult busRouteResult, int i) {

        }

        @Override
        public void onDriveRouteSearched(DriveRouteResult result, int code) {
            if (code == 1000 && result != null && result.getPaths() != null && result.getPaths().size() > 0) {
                if (aMap == null) {
                    return;
                }

                List<DrivePath> paths = result.getPaths();
                //创建存储坐标点的集合
                List<LatLonPoint> latLonPoints = new ArrayList<>();
                List<LatLng> planLatLngs = new ArrayList<>();

                //遍历获取规划的所有路线坐标点
                for (DriveStep mDriveStep : paths.get(0).getSteps()) {
                    for (LatLonPoint mLatLonPoint : mDriveStep.getPolyline()) {
                        latLonPoints.add(mLatLonPoint);
                        latLngs.add(new LatLng(mLatLonPoint.getLatitude(), mLatLonPoint.getLongitude()));
                        planLatLngs.add(new LatLng(mLatLonPoint.getLatitude(), mLatLonPoint.getLongitude()));
                    }
                }

                //无纹理纯色路线
//                DrivePath drivePath = paths.get(0);
//                PlanRouteOverlay overlay = new PlanRouteOverlay(context, aMap, drivePath,
//                        result.getStartPos(), result.getTargetPos(), latLonPoints);
//                overlay.setThroughPointIconVisibility(false);//隐藏途径点
//                overlay.setNodeIconVisibility(false);//设置节点marker是否显示
//                overlay.setIsColorfulline(false);//是否用颜色展示交通拥堵情况，默认true
//                overlay.addToMap();
//                overlay.zoomToSpan();

                //带纹理纯色路线
                aMap.addPolyline(new PolylineOptions()
                        //路线坐标点的集合
                        .addAll(planLatLngs)
                        //线的宽度
                        .width(20)
                        .setCustomTexture(BitmapDescriptorFactory.fromResource(R.drawable.icon_path_gray))
                );

                setRealityRouteInfo(orderEntity);

//                aMap.animateCamera(CameraUpdateFactory.newLatLngBounds(new LatLngBounds(
//                        new LatLng(result.getStartPos().getLatitude(), result.getStartPos().getLongitude()),
//                        new LatLng(result.getTargetPos().getLatitude(), result.getTargetPos().getLongitude())), 200));
            } else {
                MLog.d("api", "路线规划失败");
            }
        }

        @Override
        public void onWalkRouteSearched(WalkRouteResult walkRouteResult, int i) {

        }

        @Override
        public void onRideRouteSearched(RideRouteResult rideRouteResult, int i) {

        }
    }

    private class OnRealListener implements RouteSearch.OnRouteSearchListener {

        @Override
        public void onBusRouteSearched(BusRouteResult busRouteResult, int i) {

        }

        @Override
        public void onDriveRouteSearched(DriveRouteResult result, int code) {
            if (code == 1000 && result != null && result.getPaths() != null && result.getPaths().size() > 0) {//获取规划路线成功,获取到的是了,路线坐标点的集合
                if (aMap == null)
                    return;

                List<DrivePath> paths = result.getPaths();
                //创建存储坐标点的集合
                List<LatLonPoint> latLonPoints = new ArrayList<>();

                //遍历获取规划的所有路线坐标点
                for (DriveStep mDriveStep : paths.get(0).getSteps()) {
                    for (LatLonPoint mLatLonPoint : mDriveStep.getPolyline()) {
                        latLonPoints.add(mLatLonPoint);
//                        latLngs.add(new LatLng(mLatLonPoint.getLatitude(), mLatLonPoint.getLongitude()));
                    }
                }

                DrivePath drivePath = result.getPaths().get(0);
                RealRouteOverlay overlay = new RealRouteOverlay(context,
                        aMap,
                        drivePath,
                        result.getStartPos(),
                        result.getTargetPos(),
                        latLonPoints);
                overlay.setThroughPointIconVisibility(false);//隐藏途径点
                overlay.setNodeIconVisibility(false);//设置节点marker是否显示
                overlay.setIsColorfulline(false);//是否用颜色展示交通拥堵情况，默认true
                overlay.addToMap();
                overlay.zoomToSpan();
            } else {
                MLog.d("api", "路线规划失败");
            }
        }

        @Override
        public void onWalkRouteSearched(WalkRouteResult walkRouteResult, int i) {

        }

        @Override
        public void onRideRouteSearched(RideRouteResult rideRouteResult, int i) {

        }
    }

    private MarkerOptions createMarker(LatLng latLng, String title, int type) {
        View view = LayoutInflater.from(context).inflate(R.layout.layout_marker_custom, null);
        TextView nameTv = view.findViewById(R.id.name);
        nameTv.setText(title);
        TextView typeTv = view.findViewById(R.id.type);
        ImageView dot = view.findViewById(R.id.dot);
        switch (type) {
            case 1:
                typeTv.setVisibility(View.VISIBLE);
                typeTv.setBackgroundColor(Color.parseColor("#FF4B10"));
                typeTv.setText("装");
                dot.setImageResource(R.drawable.start_point_dot);
                break;

            case 2:
                typeTv.setVisibility(View.VISIBLE);
                typeTv.setBackgroundColor(Color.parseColor("#06C764"));
                typeTv.setText("卸");
                dot.setImageResource(R.drawable.end_point_dot);
                break;
            case 3:
                typeTv.setVisibility(View.GONE);
                dot.setImageResource(R.mipmap.icon_driver_driving);
                break;
        }

        BitmapDescriptor markIcon = BitmapDescriptorFactory.fromView(view);
        return new MarkerOptions().position(latLng).icon(markIcon);
    }
}
